package com.swotxu.mall.ssoclient.controller;

import com.swotxu.mall.ssoclient.conf.SSOConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Date: 2021/3/16 20:55
 * @Author: swotXu
 */
@Slf4j
@Controller
public class HelloController {

    @Autowired
    SSOConfig ssoConfig;

    /**
     * 无需登录即可访问
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * 需登录即可访问
     * @param model
     * @param session
     * @param token 由登陆认证服务器跳转回的地址中，携带 token
     * @return
     */
    @GetMapping("/employees")
    public String employees(Model model, HttpSession session
            , @RequestParam(value = "_token", required = false) String token) {
        String loginUser = (String) session.getAttribute("loginUser");

        if (StringUtils.isEmpty(loginUser) && !StringUtils.isEmpty(token)) {
            // 根据token获取用户信息
            RestTemplate restTemplate = new RestTemplate();
            loginUser = restTemplate.getForObject(ssoConfig.getFullUrl(ssoConfig.getUriUserinfo()) + "?token=" + token, String.class);
            session.setAttribute("loginUser", loginUser);
            session.setAttribute("token", token);
        }
        // 未登录，跳转到登陆服务器
        if (StringUtils.isEmpty(loginUser)) {
            String url = ssoConfig.getFullUrl(ssoConfig.getUriLogin()) + "?redirect_url=" + ssoConfig.getRedirectUrl();
            log.info("当前请求未登录，转到登陆服务器！{}", url);
            return "redirect:" + url;
        }
        List<String> emps = new ArrayList<>();
        emps.add("测试用户");
        emps.add(loginUser);
        model.addAttribute("emps", emps);
        return "list";
    }

    @ResponseBody
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        String token = (String) session.getAttribute("token");

        RestTemplate restTemplate = new RestTemplate();
        Boolean isOk = restTemplate.getForObject(ssoConfig.getFullUrl(ssoConfig.getUriLogout()) + "?token=" + token, Boolean.class);
        log.info("{}", isOk);

        session.setAttribute("loginUser", null);
        session.invalidate();

        return "退出成功!";
    }
}
